import { _decorator, Component, Node, RichText } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('TimerCtrl2')
export default class TimerCtrl2 extends Component {
    

    @property(RichText)
    timeRichText: RichText = null

    private _second: number = 0
    private callbacks: Set<Function> = new Set()
    private interval = null

    public init(second: number) {
        console.log("TimeCtl.init(), second:"+ second)
        this._second = second
        this.callbacks = new Set()

        this.setViewTimeNum(this._second)
        // 启动定时
        this.interval = setInterval(this.timeCallback.bind(this), 1000);
    }

    private timeCallback() {
        this._second--
        // 触发超时回调
        if (this._second < 0) {
            clearInterval(this.interval)    // 关闭定时
            console.log('run callback')
            this.callbacks.forEach(callback => {
                callback()
            })
        } else {
            this.setViewTimeNum(this._second)
        }
    }

    private setViewTimeNum(second: number) {
        let timerText = `<color=#333333>${second}</color>`
        // let timerText = "00"
        this.timeRichText.string = timerText
        // console.log("setViewTimeNum, timerText:"+ timerText)
        console.log("setViewTimeNum, this.timeRichText:"+ this.timeRichText.string)
    }

    public addTimeoutListener(callback: Function) {
        if (!callback) {
            return
        }
        if (!this.callbacks.has(callback)) {
            this.callbacks.add(callback)
        }
    }

    public clearTimer() {
        // console.log('timer ctrl clearTimer')
        clearInterval(this.interval)
    }

    onDestroy(): void {
        // console.log('timer ctrl on destory')
        clearInterval(this.interval)
    }

}


